<?php
/* 处理跨域问题 */
header("Access-Control-Allow-Origin: *");
/* 数据库操作工具类 */
require('connet.php'); // 依赖于该连接
if ($conn->connect_error) {
  die('数据库连接失败');
}
class SQLTools
{
  /* public or private */
  /* 计算条数 */
  public static function rowTB($_conn, $_tableName, $_condition = null)
  {
    $sql = "SELECT * FROM $_tableName";
    if (isset($_condition)) {
      $sql = $sql . " WHERE $_condition";
    }
    $result = mysqli_query($_conn, $sql);
    return mysqli_num_rows($result);
  }
  /* 判断是否存在 */
  public static function existTB($_conn, $_tableName, $_condition = null)
  {
    return SQLTools::rowTB($_conn, $_tableName, $_condition) > 0;
  }
  /* 创建数据库 */
  public static function createDB($_conn, $_dbName)
  {
    return mysqli_query($_conn, "CREATE DATABASE ${_dbName}");
  }
  /* 创建数据表 */
  public static function createTB($_conn, $_TbName, $_TBString)
  {
    return mysqli_query($_conn, "CREATE TABEL ${_TbName}(
    $_TBString
    )");
  }
  /* 插入数据 */
  public static function insertTB($_conn, $_TbName, $_TBKeys, $_TBValues)
  {
    //var_dump("INSERT INTO `$_TbName`($_TBKeys)VALUES($_TBValues)");
    return mysqli_query($_conn, "INSERT INTO `$_TbName`($_TBKeys)VALUES($_TBValues)");
  }
  /* 查询数据 */
  public static function queryTB($_conn,  $table_name, $col_name = "*", $key = null, $value = null, $limit_start = null, $limit_end = null)
  {
    $sql = "SELECT $col_name FROM $table_name";
    if (isset($key) &&  isset($value)) {
      if (is_string($value)) {
        $sql .= " WHERE $key = '$value'";
      } else {
        $sql .= " WHERE $key = $value";
      }
    }
    if (isset($limit_start) && isset($limit_end)) {
      $sql .= " limit $limit_start,$limit_end";
    }
    return mysqli_query($_conn, $sql);
  }
  /* 更新数据 */
  public static function updateTB($_conn, $_tableName, $kv, $condition = null)
  {
    $sql = "UPDATE $_tableName SET $kv";
    if ($condition != null) {
      $sql .= " WHERE $condition";
    }
    return mysqli_query($_conn, $sql);
  }
  /* 清空表 */
  public static function clearTB($_conn, $_tableName)
  {
    $sql = "DELETE FROM $_tableName";
    return mysqli_query($_conn, $sql);
  }
  /* 删除指定数据 */
  public static function deleteTB($_conn, $_tableName, $_kv)
  {
    $sql = "DELETE FROM $_tableName WHERE $_kv";
    return mysqli_query($_conn, $sql);
  }
  /* 清空数据库 */
  public static function deleteDB($_conn, $_dbName)
  {
    $sql = "DROP DATABASE $_dbName";
    return mysqli_query($_conn, $sql);
  }
  /* mysql uuid */
  public static $SQL_UUID = "REPLACE(UUID(),'-','')";
  /* mysql uuid add line*/
  public static $SQL_UUID2 = "UUID()";
}

/* 批量查询处理 */
/* sql操作工具 */


function sql_queryAll($conn, $table_name, $col_name = "*", $key = null, $value = null, $limit_start = null, $limit_end = null, $auto_echo = true,$_exclude=null)
{
  $arr = array();
  $finally_data = array("msg" => "查询成功!", "code" => "2000", "data" => array());
  // $re = $sql_t->queryTB($conn,$table_name,$col_name,$key,$value,$limit_start,$limit_end);
  // while($temp = $re->fetch_assoc()){
  //   array_push($arr,$temp);
  // }
  // // var_dump($arr);
  // echo json_encode_mz_urlencode($arr);
  $condition = null;
  if(isset($key)&&isset($value)){
    if(is_string($value)){
      $condition = "$key='$value'";
    }else {
      $condition = "$key=$value";
    }
  }
  $finally_data["count"] = SQLTools::rowTB($conn, $table_name,$condition);
  if ($finally_data["count"] > 0) {
    $arr = array();
    $re = SQLTools::queryTB($conn, $table_name, $col_name, $key, $value, $limit_start, $limit_end);
    while ($temp = $re->fetch_assoc()) {
      if(isset($_exclude)){
        foreach($_exclude as $_item){
          unset($temp[$_item]);
        }
      }
      array_push($arr, $temp);
    }
    // var_dump($arr);
    $finally_data["data"] = $arr;
    if (isset($limit_start) && $limit_end) {
      $finally_data["page"] = $limit_start + 1;
      $finally_data["size"] = $limit_end;
    }
  } else {
    $finally_data["msg"] = "查询结果为空!";
    $finally_data["code"] = "2001";
  }
  if ($auto_echo) {
    echo json_encode_mz_urlencode($finally_data);
  } else {
    return $finally_data;
  }
}
/**************************************************************
 *
 *    处理因为数组元素中含有中文乱码时的问题
 *    @param    string    &$array        要处理的字符串
 *    @param    string    $function    要执行的函数
 *    @return boolean    $apply_to_keys_also        是否也应用到key上
 *    @access public
 *
 *************************************************************/
function arrayRecursive(&$array = array(), $function = 'urlencode', $apply_to_keys_also = true)
{
  foreach ($array as $key => $value) {
    if (is_array($value)) {
      arrayRecursive($array[$key], $function, $apply_to_keys_also);
    } else {
      $array[$key] = $function($value);
    }
    if ($apply_to_keys_also && is_string($key)) {
      $new_key = $function($key);
      if ($new_key != $key) {
        $array[$new_key] = $array[$key];
        unset($array[$key]);
      }
    }
  }
}

/**
 * 处理因为数组元素中含有中文乱码问题时，json_encode优化方法
 * @param $array
 * @return string
 */
function json_encode_mz_urlencode($array)
{
  // arrayRecursive($array); // 处理数组含有中文乱码的问题,如果乱码请解开此注释。
  $json = json_encode($array);
  return urldecode($json);
}

function html2text($str)
{

  $str = preg_replace("//i", ">>>>", $str);

  $str = preg_replace("/<\\/?p>/i", ">>>>", $str);

  $str = preg_replace("/<\\/?td>/i", "", $str);

  $str = preg_replace("/<\\/?div>/i", ">>>>", $str);

  $str = preg_replace("/<\\/?blockquote>/i", "", $str);

  $str = preg_replace("/<\\/?li>/i", ">>>>", $str);

  $str = preg_replace("/ /i", " ", $str);

  $str = preg_replace("/ /i", " ", $str);

  $str = preg_replace("/&/i", "&", $str);

  $str = preg_replace("/&/i", "&", $str);

  $str = preg_replace("/", "<", $str);

  $str = preg_replace("/", "<", $str);

  $str = preg_replace("/“/i", '"', $str);

  $str = preg_replace("/&ldquo/i", '"', $str);

  $str = preg_replace("/‘/i", "'", $str);

  $str = preg_replace("/&lsquo/i", "'", $str);

  $str = preg_replace("/'/i", "'", $str);

  $str = preg_replace("/&rsquo/i", "'", $str);

  $str = preg_replace("/>/i", ">", $str);

  $str = preg_replace("/>/i", ">", $str);

  $str = preg_replace("/”/i", '"', $str);

  $str = preg_replace("/&rdquo/i", '"', $str);

  $str = strip_tags($str);

  $str = html_entity_decode($str, ENT_QUOTES, "utf-8");

  $str = preg_replace("/.*?;/i", "", $str);

  return $str;
}


/*生成唯一标志
*sha1 + base64 的 Token
*/
function  create_token()
{
  $v = 1;
  $key = mt_rand();
  $hash = hash_hmac("sha1", $v . mt_rand() . time(), $key, true);
  $hash2 = hash_hmac("sha1", rand(0, 9999999) . time() . mt_rand(), $key, true);
  return str_replace('=', '', strtr(base64_encode($hash . $hash2), '+/', '-_'));
}

/* 生成一个数据库里面不存在的uuid 如果存在递归 */
function create_token_sql($_conn, $_tableName, $_uuid_key)
{
  $uuid = create_token();
  $num = SQLTools::rowTB($_conn, $_tableName, "$_uuid_key='$uuid'"); // 存在的uuid?
  return $num == 0 ? $uuid : create_token_sql($_conn, $_tableName, $_uuid_key); // 不存在返回，存在就递归
}
/* 获取请求头信息 */
function get_request_headers()
{
  $headers = [];
  foreach ($_SERVER as $name => $value) {
    if (substr($name, 0, 5) == 'HTTP_') {
      $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
    }
  }
  return $headers;
}
